/*
 * 文件名称：AddResponseHeaderFilter.java
 * 系统名称：[系统名称]
 * 模块名称：[模块名称]
 * 软件版权：Copyright (c) 2011-2019, liming20110711@163.com All Rights Reserved.
 * 功能说明：[请在此处输入功能说明]
 * 开发人员：Rushing0711
 * 创建日期：20190109 05:18
 * 修改记录：
 * <Version>        <DateSerial>        <Author>        <Description>
 * 1.0.0            20190109-01         Rushing0711     M201901090518 新建文件
 ********************************************************************************/
package com.ishanshan.gateway.filter;

import com.google.gson.Gson;
import com.ishanshan.gateway.auth.AuthResponse;
import com.ishanshan.gateway.auth.LoginData;
import com.ishanshan.gateway.auth.LoginResponse;
import com.ishanshan.gateway.cache.CacheUtil;
import com.ishanshan.gateway.converter.JsonConverter;
import com.ishanshan.gateway.exception.GatewayException;
import com.ishanshan.gateway.exception.GatewayStatus;
import com.ishanshan.gateway.jwt.JwtAuthConstants;
import com.ishanshan.gateway.jwt.JwtTokenUtil;
import com.ishanshan.gateway.util.FilterUtils;
import com.ishanshan.gateway.util.SysNameUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.POST_TYPE;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.SEND_RESPONSE_FILTER_ORDER;

/**
 * 后置处理.
 *
 * <p>创建时间: <font style="color:#00FFFF">20190109 05:18</font><br>
 * [请在此输入功能详述]
 *
 * @author Rushing0711
 * @version 1.0.0
 * @since 1.0.0
 */
@Component
@Slf4j
public class PostFilter extends ZuulFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private CacheUtil cacheUtil;

    @Override
    public String filterType() {
        return POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return SEND_RESPONSE_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        if (!requestContext.sendZuulResponse()) {
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        if (JwtAuthConstants.isAuthLogin(request)) {
            String sysName = SysNameUtil.getSysName();
            String responseBody = FilterUtils.getResponseBody();
            LoginResponse loginResponse = JsonConverter.convert(responseBody,LoginResponse.class);
            if(loginResponse.getErrorCode() == 0){
                LoginData loginData = loginResponse.getData();
                if("1".equals(loginData.getIsCheckLogin()) && !"0".equals(loginData.getIsAlongClient()) && cacheUtil.hasToken(loginData.getUserId())){
                    throw new GatewayException(GatewayStatus.GATEWAY_HAS_LOGING);
                }
                String jwtToken =  cacheUtil.saveToken(loginData);
                loginData.setJwtToken(jwtToken);
            }
            Gson gson = new Gson();
            requestContext.setResponseBody(gson.toJson(loginResponse));
        } else if (JwtAuthConstants.isAuthSession(request)) {
            String jwtToken = jwtTokenUtil.fetchToken(request);
            LoginData loginData = jwtTokenUtil.getLoginData(jwtToken);
            String sysName = SysNameUtil.getSysName();
            String responseBody = FilterUtils.getResponseBody();
            AuthResponse authResponse = JsonConverter.convert(responseBody,AuthResponse.class);
            if(authResponse.getErrorCode() == 0){
                cacheUtil.saveAuthContent(authResponse.getData(),loginData,sysName);
                cacheUtil.saveSessionConent(authResponse.getData(),loginData,sysName);
            }
        } else if(JwtAuthConstants.isAuthLogout(request)) {
            String jwtToken = jwtTokenUtil.fetchToken(request);
            if(jwtTokenUtil.validateToken(jwtToken)){
                cacheUtil.clean(jwtToken, SysNameUtil.getSysName());
            }
        }else if(JwtAuthConstants.isAuthChange(request)){//切换Token
            String jwtToken = jwtTokenUtil.fetchToken(request);
            if(jwtTokenUtil.validateToken(jwtToken)){
                cacheUtil.clean(jwtToken, SysNameUtil.getSysName());
            }
            String responseBody = FilterUtils.getResponseBody();
            LoginResponse loginResponse = JsonConverter.convert(responseBody,LoginResponse.class);
            if(loginResponse.getErrorCode() == 0){
                LoginData loginData = loginResponse.getData();
                if("1".equals(loginData.getIsCheckLogin()) && !"0".equals(loginData.getIsAlongClient()) && cacheUtil.hasToken(loginData.getUserId())){
                    throw new GatewayException(GatewayStatus.GATEWAY_HAS_LOGING);
                }
                jwtToken =  cacheUtil.saveToken(loginData);
                loginData.setJwtToken(jwtToken);
            }
            Gson gson = new Gson();
            requestContext.setResponseBody(gson.toJson(loginResponse));
        }
        requestContext.getResponse().setHeader("Trace-ID", TraceContext.traceId());
        return null;
    }


}
